﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZMA._controls;
using BIZModel;
using BL.BIZControls;
using System.Web.Security;
using BIZMA.BL.Security;

namespace BIZMA._controls.Users
{
    public partial class List_Users : BIZListControl, IBIZControlDefaultMethods
    {
        #region Default
        public void DefaultListLoad()
        {
            LoadUsers();
        }

        public void DefaultListLoad(Guid Id, string loadByType)
        {
                throw new NotImplementedException();
        }

        public void DefaultEditNew()
        {
            throw new NotImplementedException();
        }

        public void DefaultEditNew(Guid Id, string editByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditLoad(Guid Id)
        {
            throw new NotImplementedException();
        }

        #endregion

        

        private bool CanAddUserPopup { get { return ViewState["CanAddUserPopup"] != null ? (bool)ViewState["CanAddUserPopup"] : false; } set { ViewState["CanAddUserPopup"] = value; } }

        //OLIKA ID properties som styr frågan för listan tex om man ska hämta utifrån EmployeeId eller PlanningId
        //Styrs av publika metoder
        //--

        //Olika filter för frågan till listan kan tex vara om man ska visa alla eller aktiva, eller datum mmm
        //Filter sätter man innan man kör de publika metorder som sätter ID properties som finns ovan
        /// <summary>
        /// Sök efter användare som innehåller detta
        /// </summary>
        public string FilterBy_FirstName { get { return ViewState["FilterBy_FirstName"] != null ? (string)ViewState["FilterBy_FirstName"] : ""; } set { ViewState["FilterBy_FirstName"] = value; } }
        public string FilterBy_LastName { get { return ViewState["FilterBy_LastName"] != null ? (string)ViewState["FilterBy_LastName"] : ""; } set { ViewState["FilterBy_LastName"] = value; } }
        
        #region This dialog
        protected void Page_Load(object sender, EventArgs e)
        {
    

        }

        protected override void OnInit(EventArgs e)
        {
            base.ActionDropDown = ddlAction;
            base.ListControl = lv;

            base.OnInit(e);

            base.NeedsData += new NeedsDataHandler(List_Users_NeedsData);

            //här gör man alla init inställningar typ lägga till eventhandlers och annat som styr sidan

            if (ContainerControl != null)
            {
                ContainerControl.Title = "Användare";
                ContainerControl.ShowButtons(false, false, false, false);

                if (ModalContainerControl != null)
                {
                    ModalContainerControl.Width = 800;
                    ModalContainerControl.Height = 500;
                }

               
            }

            CanAddUserPopup = mcUser.CanAddPopupControl(BIZControl.User);
            BaseBL.BtnOpenEnabled(btnNew, CanAddUserPopup, ViewState);
            mcUser.ModalClosing += new ModalControlClosing(mcUser_ModalClosing);

            ListDataBound += new EventHandler<ListViewItemEventArgs>(List_Users_ListDataBound);
        }

  



        void mcUser_ModalClosing(object sender, EventArgs e)
        {
            LoadList(false);
        }

        void List_Users_NeedsData(bool sorting)
        {
            LoadList(sorting);
        }


        private void FillActionList()
        {
            ddlAction.Items.Clear();

            ddlAction.Items.Add(new ListItem("--Välj åtgärd--", "-"));
            if (PickerControl)
            {
                ddlAction.Items.Add(new ListItem("Välj", "SEL"));
                ddlAction.Items.Add(new ListItem("-------", "-"));
                ddlAction.SelectedValue = "SEL";
            }
            
            if(SecurityBL.HasSysFunction(SecurityBL.SYSFUNCTION_SYSTEM_USERADMIN))
                ddlAction.Items.Add(new ListItem("Radera", "DEL"));

        }

        #endregion
        #region list

        /// <summary>
        /// Här rensas alla id properties som används för frågan till listan
        /// </summary>
        private void ResetIdProperties()
        {
            lv.DataSource = null;
            lv.DataBind();
        }

        //Publika metoder som underliggande sida/kontroll kan ropa på för att ladda kontrollen
        public void LoadUsers()
        {


            ResetIdProperties();
            LoadList(true);

        }

        public void Clear()
        {
            ResetIdProperties();
        }


        /// <summary>
        /// Metod som ansvarar för att fylla listan med värden utifrån vilken publik load metod som körts innan
        /// </summary>
        /// <param name="sorting">Talar om ifall sortering ska ändras eller om man ska använda tidigare sortering</param>
        private void LoadList(bool sorting)
        {
            if (!InitLoaded)
            {
                //Gör sådant som man gör på pageload här typ fyll "statisk" dropdown med värden mm 
                InitLoaded = true;
                FillActionList();
            }


            BIZMAEntities ent = BaseBL.GetEnt();

            IQueryable<BIZModel.UserProfile> query = ent.UserProfiles;

            if (query != null)
            {
                if (FilterBy_FirstName != "")
                {
                    query = query.Where(q => q.FirstName.Contains(FilterBy_FirstName));
                }

                if (FilterBy_LastName != "")
                {
                    query = query.Where(q => q.LastName.Contains(FilterBy_LastName));
                }
            }

            lv.DataSource = (from BIZModel.UserProfile P in query
                             select new { P.UserId, P.FirstName, P.LastName, 
                                 Phone = P.UserPhoneNumbers.FirstOrDefault(q => q.PhoneNumberTypeKey == BaseBL.PHONETYPE_MOBILE).Number,
                                 Email = P.UserAdresses.FirstOrDefault(q => q.AddressTypeKey == BaseBL.ADDRESSTYPE_ADDRESS).Addresses.Email,
                                 UserName = P.aspnet_Users.UserName});

            lv.DataBind();

            if (!sorting)
                lv.ReSort(ViewState);
        }

        void List_Users_ListDataBound(object sender, ListViewItemEventArgs e)
        {
            LinkButton lkb1 = (LinkButton)e.Item.FindControl("lkb1");

            lkb1.Text = string.IsNullOrEmpty( ((string)DataBinder.Eval(e.Item.DataItem, "FirstName"))) ? ((string)DataBinder.Eval(e.Item.DataItem, "UserName")) : ((string)DataBinder.Eval(e.Item.DataItem, "FirstName"));
        }

        #endregion

        #region detail dialog
        protected void OpenDetail_Command(object sender, CommandEventArgs e)
        {
            if (HandleListClickEvents)
            {
                CallHandleClick(this, Guid.Parse(e.CommandArgument.ToString()), null);
            }
            else
            {                
                if (CanAddUserPopup)
                {
                    mcUser.AddDefaultEditLoad(BIZControl.User, Guid.Parse(e.CommandArgument.ToString()));
                }
            }

        }

        protected void btnNew_Command(object sender, CommandEventArgs e)
        {
            if (HandleNewClickEvent)
            {
                CallNewHandleClick(this, Guid.Empty, null);
            }
            else
            {
                if (CanAddUserPopup)
                {
                    mcUser.AddDefaultEditNew(BIZControl.User);
                }
            }
        }

        #endregion

        protected void btnSel_Command(object sender, CommandEventArgs e)
        {
            SelectedItems = new List<Guid>();
            SelectedItems.Add(Guid.Parse(e.CommandArgument.ToString()));

            CallListSelect(this, null, MultipleSelect, SelectedItems);

        }

        protected void btnAction_Click(object sender, EventArgs e)
        {
            if (ddlAction.SelectedValue != "-")
            {
                if (ddlAction.SelectedValue == "SEL")
                {
                    var selectedKeys = lv.GetSelectedDataKeys("chkSel");
                    SelectedItems = new List<Guid>();
                    foreach (DataKey dk in selectedKeys)
                    {
                        Guid contactId = Guid.Parse(dk.Value.ToString());
                        SelectedItems.Add(contactId);
                    }

                    CallListSelect(this, null, MultipleSelect, SelectedItems);


                    
                }
                else
                {

                    var selectedKeys = lv.GetSelectedDataKeys("chkSel");
                    BIZMAEntities ent = BaseBL.GetEnt();

                    if (ddlAction.SelectedValue == "DEL")
                    {
                        foreach (DataKey dk in selectedKeys)
                        {

                            Guid userId = Guid.Parse(dk.Value.ToString());
                            UserProfile user = ent.UserProfiles.FirstOrDefault(q => q.UserId == userId);

                            if (user.aspnet_Users != null)
                            {

                                if (Membership.DeleteUser(user.aspnet_Users.UserName, true))
                                {
                                    //Raderas via FK på aspnet_Users
                                   // ent.DeleteObject(user);
                                }
                            }
                            else
                            {
                                ent.DeleteObject(user);
                            }

                        }
                    }

                    ent.SaveChanges();
                }
            }

            if (ddlAction.SelectedValue != "SEL")
            {
                LoadList(false);
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            FilterBy_FirstName = txtSearchFirstName.Text;
            FilterBy_LastName = txtSearchLastName.Text;

            LoadList(true);
        }


    }
}